package com.itydl.a03.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author ydl
 * @version 实现汉子到拼音的转换工具类
 */

public class PinYinUtils {

    /**
     * 获取当前汉子的拼音
     * @param str
     */
    public static String getyPinyin(String str) {//杨童鞋
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置无音标
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);//结果为大写字母

        StringBuffer sb = new StringBuffer();

        char[] toCharArray = str.toCharArray();
        for (int i = 0; i < toCharArray.length; i++) {

            char c = toCharArray[i];//杨--杨，dao--d  a  0；%--%
            //判空格,如果带有空格不添加
            if(Character.isWhitespace(c)){
                continue;
            }
            if(c>-128 && c<127){
                sb.append(c);//对于特殊字符进行拼接
            }else{
                //汉子字符
                try {
                    //将汉子转为拼音  杨--YANG；可能出现多音字情况，直接取第一个位置
                    String s = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
                    sb.append(s);
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                }
            }
        }

        return sb.toString();
    }
}
